# -*- coding: utf-8 -*-

import os
import xlrd


#-------------project bag---------------
from log import logger
import config


CurrentPath=os.path.dirname(os.path.dirname(__file__))

Excel = 0

def open_excel():
	global Excel
	path = CurrentPath + config.getConfig('excel','datapath')
	data = xlrd.open_workbook(path)
	logger.info('succeed to read excel')
	Excel = data
	return data

def get_sheet_data(sheet_name):
    global Excel
    sheet_list = []
    if type(sheet_name) == str:
    	logger.info('sheet_name must be a string')
    if not sheet_name.decode('utf-8') in Excel.sheet_names():
    	logger.info('error: there have no %s ' % (sheet_name))
    sheet = Excel.sheet_by_name(sheet_name)
    num = sheet.nrows
    index = sheet.row_values(0)
    for i in xrange(num):
    	sheet_dict = {}
    	if i == 0:
    		continue
    	value = sheet.row_values(i)
    	sheet_dict[index[0]] = int(value[0])
    	sheet_dict[index[1]] = str(value[1])
    	sheet_list.append(sheet_dict)
    return sheet_list
	




#--------------------------test----------------------------------

def Found_excel_row(table,row_value,col_value = ''):      #第几行
    r = table.nrows
    if col_value == '':
        for i in xrange(r):
            if table.cell(i,0).value == row_value:
                return i
    else:
        j = Found_excel_col(table, col_value)
        for i in xrange(r):
            if table.cell(i,j).value == row_value:
                return i
    print 'cant not found the value on the row'
    return

def Found_excel_col(table,col_value, row_value = ''):     #第几列
    r = table.ncols
    if row_value == '':
        for i in xrange(r):
            if table.cell(0,i).value == col_value:
                return i
    else:
        j = Found_excel_row(table, row_value)
        for i in xrange(r):
            if table.cell(i,j).value == col_value:
                return i
    print 'cant not found the value on the col'
    return

def Found_report_excel_value(table,row_value,col_value):
    row = Found_excel_row(table, row_value, 'code')
    col = Found_excel_col(table, col_value)
    value = table.cell(row,col).value
    return value